open Unix

open Common
open Io
open Ftp_session
open Ftp_core

type ftp_file_info =
  | F_DIR
  | F_REG

let is_dir session pathname =
  let cc = session.cc in
  let reply_code = change_work_dir cc pathname in
  ignore (change_work_dir cc session.workdir);
  match reply_code.[0] with
  | '2' ->
      true
  | _ ->
      false

let rec get_absolute_path prefix_dir pathname =
  assert (String.compare prefix_dir "" <> 0 && prefix_dir.[0] = '/' &&
          prefix_dir.[String.length prefix_dir - 1] = '/' &&
          String.compare pathname "" <> 0 &&
          pathname.[String.length pathname - 1] = '/');
  if not (Filename.is_relative pathname) then  (* pathname is absolute *)
    (
     let pathname_len = String.length pathname in
     if pathname_len=1 then
       "/"
     else
       get_absolute_path "/" (String.sub pathname 1 (pathname_len-1))
    ) 
  else                                         (* pathname is relative *)
    (
     let pathname_len = String.length pathname in
     let ret_path = ref prefix_dir in
     let ret_path_len = ref (String.length prefix_dir) in
     let idx_pre = ref (-1) in
     let idx = ref (String.index pathname '/') in
     let loop_cond = ref true in
     while !loop_cond do
       let subdir = String.sub pathname (!idx_pre+1) (!idx-(!idx_pre)-1) in
       print_debug_msg (subdir^"\n");
       let subdir_len = String.length subdir in
       if subdir_len=2&&subdir.[0]='.'&&subdir.[1]='.' then
         (
          let last_idx = 
            try
              (String.rindex_from !ret_path (!ret_path_len-2) '/') 
            with
            | Not_found ->
                -1
          in
          if last_idx<>(-1) then 
            (
             ret_path := String.sub !ret_path 0 (last_idx+1);
             ret_path_len := last_idx+1
            )
         )
       else if subdir_len=1&&subdir.[0]='.' then
         ()
       else
         (
          ret_path := !ret_path ^ subdir ^ "/";
          ret_path_len := !ret_path_len + subdir_len + 1
         );
       if !idx = (pathname_len-1) then
         loop_cond := false
       else
         (
          idx_pre := !idx;
          idx := String.index_from pathname (!idx+1) '/'
         )
     done;
     !ret_path
    )
      
    
  
